//index.js
// 引入SDK核心类
var QQMapWX = require('../../libs/qqmap-wx-jssdk.min.js');
// 实例化API核心类
var qqmapsdk = new QQMapWX({
	key: 'OF7BZ-44PLF-7P3JX-NGDVD-OLBFZ-UVBZZ' //开发者秘钥key
});
const app = getApp()

Page({
	data: {
		true_position: '',
		refreshHeight: 0,
		flag: false,
		scrollTop: 77,
		start_y: 0,
		end_y: 0,
		items: []
	},
	gotoTab: function(e) {
		let tab = e.currentTarget.dataset.name;
		//监听点击的标签名
		let url = '../' + tab + '/' + tab;
		wx.navigateTo({
			//定向到对应的标签
			url: url
		});
	},
	touched: function(e) {
		// 触碰 scroll-view 触发，记录初始y值
		this.setData({
			flag: true,
			start_y: e.changedTouches[0].pageY
		});
	},
	moved: function(e) {
		// 手指移动触发，记录移动的y值
		if (!this.__data__.flag) return
		this.setData({
			end_y: e.changedTouches[0].pageY
		})
		let start = this.__data__.start_y;
		let end = this.__data__.end_y;
		let refreshHeight = end - start;
		// 计算y值差，确定refresh高
		if (refreshHeight <= 0) return
		this.setData({
			refreshHeight: refreshHeight,
			scrollTop: 77 - refreshHeight
		});
	},
	leaved: function(e) {
		this.setData({
			flag: false,
			refreshHeight: 0,
			scrollTop: 77
		});
		wx.startPullDownRefresh({
			success: () => {}
		});
	},
	leaved2: function(e) {},
	onLoad: function(e) {
		// 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.record" 这个 scope
		wx.getSetting({
			success(res) {
				if (!res.authSetting['scope.userLocation']) {
					wx.authorize({
						scope: 'scope.userLocation',
						success() {
							// 用户已经同意小程序使用定位功能，后续调用 scope.userLocation 接口不会弹窗询问
							// wx.getLocation();
						}
					})
				}
			}
		});
		wx.cloud.init({
			traceUser: true
		});
		wx.cloud.callFunction({
				name: 'show',
				data: {}
			})
			.then(res => {
				//拿到数据库商品数据
				this.setData({
					items: res.result.data
				});
				// console.log(this.__data__.items);
			})
			.catch(err => console.log(err));
	},
	onReady: function(e) {
		wx.getLocation({
			type: 'gcj02', // wgs84
			success: (res) => {
				qqmapsdk.reverseGeocoder({
					location: {
						latitude: res.latitude,
						longitude: res.longitude
					},
					success: (res) => {
						//获取当前地址成功					
						let address = wx.getStorageSync('address');
						if (address == '') {
							this.setData({
								true_position: res.result.address_component.street_number
							})
						} else {
							this.setData({
								true_position: address
							})
						}
					},
					fail: () => {
						console.log('reverseGeocoder failed')
					}
				})
			},
			fail: () => {
				console.log('getLocation failed')
			}
		});
		
	},
})
